package com.example.nio.netty.protoco;

import com.example.nio.netty.protoco.request.LoginRequest;
import com.example.nio.netty.protoco.request.MessageRequest;
import com.example.nio.netty.protoco.response.LoginResponse;
import com.example.nio.netty.protoco.response.MessageResponse;
import com.example.nio.netty.protoco.serializer.JsonSerializer;
import com.example.nio.netty.protoco.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import java.util.HashMap;
import java.util.Map;

public class PackageCodec {

    private Serializer serializer = new JsonSerializer();

    private Map<Byte, Class<? extends Packet>> commandMap;

    public static PackageCodec INSTANCE = new PackageCodec();


    private PackageCodec (){
        commandMap = new HashMap<>();
        commandMap.put(Command.LOGIN_REQUEST, LoginRequest.class);
        commandMap.put(Command.LOGIN_RESPONSE, LoginResponse.class);
        commandMap.put(Command.Message_Request, MessageRequest.class);
        commandMap.put(Command.Message_Response, MessageResponse.class);
    }

    public ByteBuf encode(Packet packet, ByteBuf byteBuf){
        byte[] b = serializer.encode(packet);
        byteBuf.writeBytes("xxx".getBytes());
        byteBuf.writeByte(packet.getCommand());
        byteBuf.writeInt(b.length);
        byteBuf.writeBytes(b);
        return byteBuf;
    }

    public Packet decode(ByteBuf byteBuf) {
        byteBuf.skipBytes(3);
        Byte command = byteBuf.readByte();
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        Packet packet = serializer.decode(commandMap.get(command), bytes);
        return packet;
    }
}
